<template>
  <div v-loading="loading" class="h-100 relative flex algin-center">
    <el-select
      v-model="dateValue"
      class="chart-statistics-select chart-date-type"
      @change="growthChange"
    >
      <el-option
        v-for="item in dateTextList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>

    <template v-if="isData">
      <div class="chart-range-box flex align-center">
        <i
          class="el-icon-minus tool-item"
          :class="offset === 35 ? 'disabled' : ''"
          @click="$debounce(changeRange, -1)"
        />
        <i
          class="el-icon-plus tool-item"
          :class="offset === 0 ? 'disabled' : ''"
          @click="$debounce(changeRange, +1)"
        />
      </div>
      <div ref="chart" class="w-100 h-100" style="width: 100%; height: 100%" />
    </template>
    <NullData v-else type="line" />
  </div>
</template>
<script>
  import * as echarts from 'echarts'
  import { changeDecimal, formatDate } from '@/utils/common'
  import commonMixin from './js/commonMixin'

  export default {
    mixins: [commonMixin],
    data() {
      return {
        isData: true,
        loading: false,
        dateValue: 'YEAR',
        dateTextList: [
          { value: 'YEAR', label: this.$t('YEAR') },
          { value: 'MONTH', label: this.$t('MONTH') },
          { value: 'WEEK', label: this.$t('WEEK_NAME') }
        ],
        growthData: { statType: 'YEAR', range: 36 },
        showName: {
          YEAR: 'yyyy',
          MONTH: 'MM',
          WEEK: 'dd'
        },
        offset: 0
      }
    },
    computed: {},
    created() {
      this.$nextTick(() => {
        this.renderChart(true)
      })
    },
    methods: {
      growthChange() {
        if (this.dateValue === 'YEAR') {
          this.growthData = { statType: 'YEAR', range: 36 }
        } else if (this.dateValue === 'MONTH') {
          this.growthData = { statType: 'MONTH', range: 36 }
        } else {
          this.growthData = { statType: 'WEEK', range: 36 }
        }
        this.$emit('growthChange', this.growthData)
      },
      renderChart(reset) {
        this.isData = true
        this.statusChart && this.statusChart.clear()
        this.statusChart && this.statusChart.resize()
        const colorData =
          this.getTheme === 'dark-theme'
            ? {
              all: [
                { offset: 0, color: 'rgba(43, 75, 245, 1)' },
                { offset: 1, color: 'rgba(2, 164, 255, 1)' }
              ],
              narmal: [
                { offset: 0, color: 'rgba(36, 248, 172, 1)' },
                { offset: 0.5, color: 'rgba(4, 215, 244, 1)' },
                { offset: 1, color: 'rgba(10, 218, 246, 1)' }
              ],
              fault: [
                { offset: 0, color: 'rgba(251, 65, 53, 1)' },
                { offset: 1, color: 'rgba(251, 196, 53, 1)' }
              ]
            }
            : {
              all: [
                { offset: 1, color: 'rgba(85, 144, 249, 1)' },
                { offset: 0, color: 'rgba(107, 197, 255, 1)' }
              ],
              narmal: [
                { offset: 0, color: 'rgba(94, 217, 223, 1)' },
                { offset: 1, color: 'rgba(105, 232, 203, 1)' }
              ],
              fault: [
                { offset: 1, color: 'rgba(255, 154, 87, 1)' },
                { offset: 0, color: 'rgba(255, 216, 121, 1)' }
              ]
            }
        this.offset = reset ? 0 : this.offset
        const chainRatioList = this.statisticsData.chainRatioList
        chainRatioList.sort((a, b) => new Date(a.date) - new Date(b.date))
        const xData = []
        const totalBar = []
        const normalBar = []
        const faultBar = []
        const totalLine = []
        const normalLine = []
        const faultLine = []
        const showData = chainRatioList.slice(
          -6 + this.offset,
          this.offset || chainRatioList.length
        )
        showData.forEach((i, index) => {
          i.total = Number(i.total)
          i.normal = Number(i.normal)
          i.fail = Number(i.fail)
          if (index === 0) return
          if (this.dateValue === 'WEEK') {
            xData.push(this.$t('NEAR_WEEK', { msg: 6 - index - this.offset }))
          } else {
            const name = formatDate(i.name, this.showName[this.dateValue])
            xData.push(name)
          }
          totalBar.push(i.total)
          normalBar.push(i.normal)
          faultBar.push(i.fail)
          const prevIndex = chainRatioList.length - 7 + index + this.offset
          const prevData = chainRatioList[prevIndex]
          totalLine.push(this.computePercent(prevData.total, i.total))
          normalLine.push(this.computePercent(prevData.normal, i.normal))
          faultLine.push(this.computePercent(prevData.fail, i.fail))
        })
        const maxNum = Math.max(...totalBar) * 2.5
        const maxPercent = Math.max(...totalLine, ...normalLine, ...faultLine)
        const minPercent = Math.min(...totalLine, ...normalLine, ...faultLine)
        const percentNum = Math.max(maxPercent, minPercent) * 2
        const _this = this
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: params => {
              let name = ''
              const htmlArr = []
              const halfLength = params.length / 2
              for (let i = 0; i < halfLength; i++) {
                const str = params[i].marker + params[i].seriesName + ': ' +
                  params[i].value + ' ' + params[i + halfLength].value + '%'
                htmlArr.push(str)
                name = params[i].name
              }
              htmlArr.unshift(name)
              return htmlArr.join('</br>')
            },
            ..._this.tooltipOptions()
          },
          legend: {
            icon: 'roundRect',
            left: 0,
            top: 5,
            itemHeight: 10,
            itemWidth: 20,
            textStyle: {
              color: _this.homeAxisText(),
              fontSize: _this.resetSize(12)
            },
            data: [
              {
                name: _this.$t('ALL_BIZ'),
                itemStyle: {
                  color: colorData.all[0].color
                }
              },
              {
                name: _this.$t('NORMAL_BIZ'),
                itemStyle: {
                  color: colorData.narmal[0].color
                }
              },
              {
                name: _this.$t('FAULT_BIZ'),
                itemStyle: {
                  color: colorData.fault[0].color
                }
              }
            ]
          },
          grid: {
            left: 40,
            right: 50,
            bottom: 25,
            top: 65
          },
          xAxis: {
            type: 'category',
            ..._this.axisOptions(),
            axisLabel: {
              interva: 0,
              fontSize: _this.resetSize(12),
              color: _this.homeAxisText()
            },
            data: xData
          },
          yAxis: [
            {
              name: _this.$t('QUANTITY_PCS'),
              position: 'left',
              type: 'value',
              max: maxNum,
              ..._this.axisOptions(),
              splitLine: {
                show: false
              },
              nameTextStyle: {
                align: 'center',
                fontSize: _this.resetSize(10),
                color: _this.homeAxisText()
              }
            },
            {
              name: _this.$t('PERCENT'),
              type: 'value',
              position: 'right',
              max: percentNum,
              min: -percentNum,
              ..._this.axisOptions(),
              nameTextStyle: {
                align: 'left',
                fontSize: _this.resetSize(10),
                color: _this.homeAxisText()
              },
              axisLabel: {
                formatter: '{value}%',
                fontSize: _this.resetSize(12),
                color: _this.homeAxisText()
              }
            }
          ],
          series: [
            {
              name: _this.$t('ALL_BIZ'),
              type: 'bar',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, colorData.all)
              },
              data: totalBar
            },
            {
              name: _this.$t('NORMAL_BIZ'),
              type: 'bar',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, colorData.narmal)
              },
              data: normalBar
            },
            {
              name: _this.$t('FAULT_BIZ'),
              type: 'bar',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, colorData.fault)
              },
              data: faultBar
            },
            {
              name: _this.$t('ALL_BIZ'),
              type: 'line',
              symbol: 'circle',
              yAxisIndex: 1,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  { offset: 0, color: 'rgba(43, 75, 245, 1)' },
                  { offset: 1, color: 'rgba(2, 164, 255, 1)' }
                ])
              },
              data: totalLine
            },
            {
              name: _this.$t('NORMAL_BIZ'),
              type: 'line',
              symbol: 'circle',
              yAxisIndex: 1,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  { offset: 0, color: 'rgba(36, 248, 172, 1)' },
                  { offset: 0.5, color: 'rgba(4, 215, 244, 1)' },
                  { offset: 1, color: 'rgba(10, 218, 246, 1)' }
                ])
              },
              data: normalLine
            },
            {
              name: _this.$t('FAULT_BIZ'),
              type: 'line',
              symbol: 'circle',
              yAxisIndex: 1,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  { offset: 1, color: 'rgba(251, 196, 53, 1)' },
                  { offset: 0, color: 'rgba(251, 65, 53, 1)' }
                ])
              },
              data: faultLine
            }
          ]
        }
        this.$nextTick(() => {
          !this.statusChart && (this.statusChart = echarts.init(this.$refs.chart))
          this.statusChart.setOption(option)
        })
      },
      computePercent(prev, cur) {
        prev = Number(prev)
        let percent = 0
        if (prev === 0) {
          percent = cur === 0 ? 0 : 100
        } else {
          percent = changeDecimal(((cur - prev) * 100) / (prev || 1), 2)
        }
        return percent
      },
      changeRange(count) {
        const offset = this.offset + count
        if (offset > 0 || offset < -35) return
        this.offset = offset
        this.renderChart()
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';

  .chart-date-type {
    right: 0;
    width: 50px !important;
  }
  .chart-range-box {
    position: absolute;
    top: 35px;
    right: 50px;
    padding: 1px 3px;
    font-size: 10px;
    border-radius: 3px;
    z-index: 3;
    cursor: pointer;
    .el-icon-minus.tool-item {
      padding-right: 3px;
      margin-right: 3px;
      @include themeify {
        border-right: 1px solid themed('homeRangeColor');
      }
    }
    @include themeify {
      background: themed('homeRangeBg') !important;
      color: themed('homeRangeColor') !important;
    }
    .disabled {
      cursor: not-allowed;
    }
  }
</style>
